#!/usr/bin/python3
# ******************************************************************************
# Copyright (c) Huawei Technologies Co., Ltd. 2021-2022. All rights reserved.
# licensed under the Mulan PSL v2.
# You can use this software according to the terms and conditions of the Mulan PSL v2.
# You may obtain a copy of Mulan PSL v2 at:
#     http://license.coscl.org.cn/MulanPSL2
# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR
# PURPOSE.
# See the Mulan PSL v2 for more details.
# ******************************************************************************/
"""
This is a helper script for working with gitee.com
"""
import os

from conf import settings
from exception import ConfigNotFoundError
from logger import logger
from . import Api


class Gitee(Api):
    """
    Gitee is a helper class to abstract gitee.com api
    """
    host = "https://gitee.com/api/v5/repos"

    def __init__(self):
        super(Gitee, self).__init__()
        self.token = os.getenv("TRACK_GITEE_TOKEN", settings.token(name="gitee"))
        if not self.token:
            raise ConfigNotFoundError(
                "Please set the 'TRACK_GITEE_TOKEN' environment variables of gitee."
            )

    async def create_issue(self, title, body):
        """
        Create issue in gitee
        """
        issues_url = f"{self.host}/{self._owner}/issues"
        parameters = self._set_token()
        parameters["repo"] = self._repo
        parameters["title"] = title
        parameters["body"] = body
        return await self._post(issues_url, parameters)

    async def create_issue_comment(self, number, body):
        """
        create issue comment
        """
        url = f"{self.host}/{self._owner}/{self._repo}/issues/{number}/comments"
        values = self._set_token()
        values["body"] = body
        logger.info(f"Add comment to issue url: {url}")
        return await self._post(url, values)

    async def create_pr_comment(self, number, body):
        """
        Post comment to the given specific PR
        """
        url = f"{self.host}/{self._owner}/{self._repo}/pulls/{number}/comments"
        values = self._set_token()
        values["body"] = body
        return self._post(url, values)
